package com.shen.add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore=new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();//获得
                    System.out.println(Thread.currentThread().getName()+"抢到车位！");
                    TimeUnit.SECONDS.sleep(2);//等待
                    System.out.println(Thread.currentThread().getName()+"离开车位！");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();//释放
                }

            }).start();
        }
        /**
         * Thread-0抢到车位！
         * Thread-1抢到车位！
         * Thread-2抢到车位！
         * Thread-0离开车位！
         * Thread-3抢到车位！
         * Thread-1离开车位！
         * Thread-4抢到车位！
         * Thread-2离开车位！
         * Thread-5抢到车位！
         * Thread-4离开车位！
         * Thread-3离开车位！
         * Thread-5离开车位！
         *
         */
    }
}
